package miiteen.sys.shiro;

import miiteen.common.json.JsonUtil;
import miiteen.core.result.ResultMessageTool;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class MtUserFilter extends org.apache.shiro.web.filter.authc.UserFilter {
    public final static String X_R = "X-Requested-With";
    public final static String X_R_VALUE = "XMLHttpRequest";

    @Override
    protected boolean onAccessDenied(ServletRequest request,
                                     ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        if (isAjax(httpServletRequest)) {
            response.getWriter().append(JsonUtil.toJsonStr(ResultMessageTool.Error(-601, "")));
            return false;
        } else {
            return super.onAccessDenied(request, response);
        }
    }

    /**
     * 判断ajax请求
     *
     * @param request
     * @return
     */
    boolean isAjax(HttpServletRequest request) {
        return StringUtils.isNotBlank(request.getContentType()) && request.getContentType().toLowerCase().contains("json");
    }
}
